/**
 * Copyright (c) OpenSpug Organization. https://github.com/openspug/spug
 * Copyright (c) <spug.dev@gmail.com>
 * Released under the AGPL-3.0 License.
 */
import React, { useRef, useEffect, useState } from 'react';
import { Row, Radio, Card, Form, Input, Empty, Select } from 'antd';
import { Breadcrumb } from 'components';
import { GetlockersList, GetControllers, GetManagement } from './service';
import Cabinet from './Cabinet';
import { set } from 'lodash';

function HomeIndex() {

  const [form] = Form.useForm();

  const [formLayout, setFormLayout] = useState('inline');
  //管理区
  const [Radiovalue, setRadiovalue] = useState(1)
  //控制器
  const [Controllers, setControllers] = useState([])
  // 管理区
  const [Management, setManagement] = useState([])
  //搜索条件
  const [SearchParams, setSearchParams] = useState({
    locker_number: "",
    physical_zone: "",
    area_name: "",
    locker_type: "",
    usage_status: ""
  });


  const onFormLayoutChange = (layout) => {
    setFormLayout(layout);
  };

  const [dataSource, setDataSource] = useState([]);

  useEffect(() => {
    let flag = parseInt(localStorage.getItem("Radiovalue")) || 2
    setRadiovalue(flag)
    GetData(SearchParams, flag)

    GetControllers().then(data => {

      if (!data.data.length) {
        setControllers([])
      }

      let res = data.data.list.map(item => {
        return {
          label: item.controller_name,
          value: item.physical_zone
        }
      })
      setControllers(res)
    })

    GetManagement().then(data => {

      if (!data.data.length) {
        setManagement([])
      }
      let res = data.data.map((item) => {
        return {
          label: item.area_name,
          value: item.area_name
        }
      })
      setManagement(res)
    })




  }, [])

  const [BtnList] = useState([
    {
      name: "在用",
      count: 0,
    },
    {
      name: "空闲",
      count: 0,
    },
    {
      name: "维修",
      count: 0,
    },
    {
      name: "脏柜",
      count: 0,
    },
  ])

  const [Total, setTotal] = useState(0)
  const hasInitialized = useRef(false);
  const GetData = (Params, flag) => {

    GetlockersList(Params).then((data) => {



      if (!data.data.list.length) {
        setDataSource([])
      }

      if (!hasInitialized.current) {
        setTotal(data.data.total)

        const statusToBtnName = {
          0: '空闲',
          6: '维修',
          8: '脏柜',
        };

        // 初始化计数器
        const countMap = {
          '空闲': 0,
          '维修': 0,
          '脏柜': 0,
          '在用': 0,
        };
        // 一次遍历统计
        data.data.list.forEach(item => {
          const status = item.usage_status;
          const btnName = statusToBtnName[status];

          if (btnName) {
            countMap[btnName]++;
          } else {
            // 非 0/6/8 都算“在用”
            countMap['在用']++;
          }
        });

        // 回写到 BtnList
        BtnList.forEach(btn => {
          btn.count = countMap[btn.name] || 0;
        });

        // for (let i = 0; i < data.data.list.length; i++) {
        //   for (let j = 0; j < BtnList.length; j++) {
        //     if (data.data.list[i].usage_status == 6 && BtnList[j].name == "维修") {

        //       BtnList[j].count++
        //     } else if (data.data.list[i].usage_status == 0 && BtnList[j].name == "空闲") {
        //       BtnList[j].count++
        //     } else if (data.data.list[i].usage_status == 8 && BtnList[j].name == "脏柜") {
        //       BtnList[j].count++
        //     } else {
        //       // BtnList[j].count++
        //       if (BtnList[j].name == "在用" && data.data.list[i].usage_status != 0 && data.data.list[i].usage_status != 6 && data.data.list[i].usage_status != 8) {
        //         BtnList[j].count++
        //       }
        //     }
        //   }
        // }

      }

      console.log('BtnList', BtnList);
      // 按管理区筛选
      const groupByField = (list, field) => {
        const groups = [...new Set(list.map(item => item[field]))];
        return groups.map(key => ({
          [field]: key,
          list: list.filter(item => item[field] === key)
        }));
      };

      if (flag === 1) {
        const buckets = groupByField(data.data.list, 'controller_name');
        console.log('控制器', buckets);
        setDataSource(buckets);
      }

      if (flag === 2) {
        const buckets = groupByField(data.data.list, 'area_name');
        console.log('最后结果', buckets);
        setDataSource(buckets);
      }

      hasInitialized.current = true;
    })
  }


  const Typebtn = [
    {
      name: "鞋柜",
      count: 0,
    },
    {
      name: "更衣柜",
      count: 0,
    }
  ]
  // 当前点击的按钮
  const [activeItem, setactiveItem] = useState("")
  // 当前点击的按钮
  const [TypeActive, setTypeActive] = useState("");


  const Seach = (item) => {




    if (item === activeItem) {
      setSearchParams({ ...SearchParams, usage_status: "" })
      GetData({ ...SearchParams, usage_status: "" }, Radiovalue)
      return setactiveItem("")
    }

    setactiveItem(prev => (prev === item ? '' : item));

    switch (item) {
      case "在用":
        setSearchParams({ ...SearchParams, usage_status: 100 })
        GetData({ ...SearchParams, usage_status: 100 }, Radiovalue)
        break;
      case "空闲":
        setSearchParams({ ...SearchParams, usage_status: 0 })
        GetData({ ...SearchParams, usage_status: 0 }, Radiovalue)
        break;
      case "维修":
        setSearchParams({ ...SearchParams, usage_status: 6 })
        GetData({ ...SearchParams, usage_status: 6 }, Radiovalue)
        break;
      case "脏柜":
        setSearchParams({ ...SearchParams, usage_status: 8 })
        GetData({ ...SearchParams, usage_status: 8 }, Radiovalue)
        break;

    }

  }


  const UpdateList = (flag) => {
    if (flag == 1) {
      hasInitialized.current = false
    }
    GetData(SearchParams, Radiovalue)

  }
  const TypeSeach = (value) => {
    if (value === TypeActive) {
      setSearchParams({ ...SearchParams, locker_type: "" })
      GetData({ ...SearchParams, locker_type: "" }, Radiovalue)
      return setTypeActive("")
    }

    setTypeActive(prev => (prev === value ? '' : value));
    if (value === "鞋柜") {
      GetData({ ...SearchParams, locker_type: value }, Radiovalue)
      setSearchParams({ ...SearchParams, locker_type: value })
    }

    if (value === "更衣柜") {
      GetData({ ...SearchParams, locker_type: value }, Radiovalue)
      setSearchParams({ ...SearchParams, locker_type: value })
    }

  }

  const ReadCard = () => {

    console.log("读卡")

  }

  return (
    <div>

      <div style={{ display: "flex" }}>


        <Card className="no-scrollbar" style={{ overflow: 'hidden', overflowY: 'scroll', maxHeight: 'calc(100vh - 130px)', minHeight: 'calc(96vh - 130px)', maxWidth: "calc(86vw - 200px)", minWidth: "calc(86vw - 200px)" }} >
          {
            dataSource.length ? <Cabinet UpdateList={UpdateList} Radiovalue={Radiovalue} data={dataSource} /> : <Empty style={{ marginTop: "20vh" }} />
          }

        </Card>


        <div style={{ marginLeft: 20, minWidth: 160 }}>
          <Form

            form={form}
            initialValues={{ layout: formLayout }}
            onValuesChange={onFormLayoutChange}

          >
            <Form.Item >
              <Radio.Group
                value={Radiovalue}
                onChange={e => {
                  setRadiovalue(e.target.value)
                  GetData(SearchParams, e.target.value)
                  localStorage.setItem("Radiovalue", e.target.value)
                }}
                options={[
                  { value: 1, label: '按控制器' },
                  { value: 2, label: '按管理区' },
                ]}
              />
            </Form.Item>
            <Form.Item >
              <Select placeholder="请选择管理区" allowClear={true} options={Management}

                onChange={(value) => {
                  console.log(value)
                  setSearchParams({ ...SearchParams, area_name: value })
                  GetData({ ...SearchParams, area_name: value }, Radiovalue)
                }}
              >

              </Select>


            </Form.Item>

            <Form.Item >
              <Select allowClear={true} placeholder="请选择控制器" options={Controllers}
                onChange={(value) => {
                  console.log("结果", value)
                  setSearchParams({ ...SearchParams, physical_zone: value })
                  GetData({ ...SearchParams, physical_zone: value }, Radiovalue)
                }}
              >

              </Select>
            </Form.Item>

            <Form.Item >
              <Input
                placeholder="请输入柜号"
                onChange={(e) => {
                  const val = e.target.value;
                  // 只允许空或数字
                  if (/^\d*$/.test(val)) {
                    setSearchParams({ ...SearchParams, locker_number: val });
                    GetData({ locker_number: val }, Radiovalue);
                  }
                }}
              />
            </Form.Item>
            <div> 总数量为 <span style={{ fontSize: 17, fontWeight: 600 }}>{Total}</span> </div>
            {
              BtnList.map((item, index) => {
                return (
                  <div key={index} className={`
                          btn 
                         flex
                          ${item.name === activeItem ? 'bgc-btn-grey' : ''}   
                        `} onClick={() => Seach(item.name)}
                        style={{display: "flex",justifyContent: "space-between"}}
                        >
                    <div style={{ display: "flex" }}>
                      <div className={item.name == '维修' ? "bgc-red Circle" : item.name == '空闲' ? "bgc-bule Circle" : item.name == '在用' ? "bgc-green Circle" : "bgc-grey Circle"} ></div>
                      <div style={{ marginLeft: 5 }}>{item.name}  </div>
                    </div>

                    <div style={{ fontSize: 13, fontWeight: 400 ,marginRight:15}}>{item.count}</div>
                  </div>
                )
              })
            }
            {
              Typebtn.map((item, index) => {
                return (
                  <div style={{paddingLeft:43}} className={`btn  ${item.name === TypeActive ? 'bgc-btn-grey' : ''} `} key={index} onClick={() => TypeSeach(item.name)}>
                    <div style={{ marginLeft: 5 }}>{item.name}</div>
                  </div>
                )
              })
            }


            <div className='btn' style={{ textAlign: "center", padding: 0, backgroundColor: "#5f82ec", color: "#fff" }} onClick={() => ReadCard()}>读卡</div>
          </Form>

        </div>
      </div>



    </div>
  )
}

export default HomeIndex